package com.biodiv.community.config;

import com.maxmind.geoip2.DatabaseReader;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author tianquan
 */
@Slf4j
@Configuration
public class GeoIPConfig {

    @Value("${geo.file}")
    private String ipFile;

    private final ResourceLoader resourceLoader;

    public GeoIPConfig(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    // @Bean
    public DatabaseReader databaseReader() throws IOException {
        log.info("Loading GeoIP database from: {}", ipFile);
        try {
            // 尝试从类路径加载资源
            Resource resource = resourceLoader.getResource("classpath:" + ipFile);
            
            // 如果资源不存在，尝试从文件系统加载
            if (!resource.exists()) {
                log.info("Resource not found in classpath, trying file system");
                resource = resourceLoader.getResource("file:" + ipFile);
            }
            
            // 如果资源仍然不存在，尝试直接从路径加载
            if (!resource.exists()) {
                log.info("Resource not found in file system, trying direct path");
                resource = resourceLoader.getResource(ipFile);
            }
            
            if (!resource.exists()) {
                throw new IOException("Could not find GeoIP database at: " + ipFile);
            }
            
            log.info("GeoIP database found at: {}", resource.getURI());
            InputStream inputStream = resource.getInputStream();
            return new DatabaseReader.Builder(inputStream).build();
        } catch (Exception e) {
            log.error("Failed to load GeoIP database", e);
            throw e;
        }
    }
}